/**
 *
 */
package com.ybkj.daijia.server.service.impl;

import com.ybkj.daijia.DateTimeUtils;
import com.ybkj.daijia.OrderNumberConfig;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.page.Pageable;
import com.ybkj.daijia.page.impl.PageImpl;
import com.ybkj.daijia.page.impl.PageRequest;
import com.ybkj.daijia.server.mapper.CompanyMapper;
import com.ybkj.daijia.server.mapper.DriverMapper;
import com.ybkj.daijia.server.mapper.DriverPaymentsRecordMapper;
import com.ybkj.daijia.server.mapper.DriverRebateEnchashmentMapper;
import com.ybkj.daijia.server.mapper.DriverRebatePaymentRecordMapper;
import com.ybkj.daijia.server.mapper.FinancialRecordMapper;
import com.ybkj.daijia.server.mapper.NoticeMapper;
import com.ybkj.daijia.server.mapper.NoticeXDriverMapper;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.DriverPaymentsRecord;
import com.ybkj.daijia.server.model.DriverRebateEnchashment;
import com.ybkj.daijia.server.model.DriverRebatePaymentRecord;
import com.ybkj.daijia.server.model.FinancialRecord;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverRebateEnchashmentService;
import com.ybkj.daijia.server.service.DriverService;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Shine
 *
 */
@Service
public class DriverRebateEnchashmentServiceImpl implements
    DriverRebateEnchashmentService {

    @Autowired
    DriverService driverService;
    @Autowired
    private DriverRebateEnchashmentMapper driverRebateEnchashmentMapper;
    @Autowired
    private DriverMapper driverMapper;
    @Autowired
    private DriverPaymentsRecordMapper driverPaymentsRecordMapper;
    @Autowired
    private SettingUtils settingUtils;
    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;
    @Autowired
    private NoticeMapper noticeMapper;
    @Autowired
    private NoticeXDriverMapper noticeXDriverMapper;
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private FinancialRecordMapper financialRecordMapper;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private DriverRebatePaymentRecordMapper driverRebatePaymentRecordMapper;

    /*
     * (non-Javadoc)
     *
     * @see com.ybkj.shop.service.AdminService#queryAll()
     */
    public Page<DriverRebateEnchashment> queryByEmploy(Long employId, String param,
        Integer page, Integer limit) {

        Pageable pageable = new PageRequest(page, limit);

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        String likeParam = null;
//        Long[] companyIds = null;
//        if (null != principal) {
//            if (!principal.isCompanyType()) {
//                companyIds = new Long[1];
//                companyIds[0] = principal.getCompanyId();
//            }
//        }

        if (StringUtils.isNotBlank(param)) {
            likeParam = "%" + param + "%";
        }
        List<DriverRebateEnchashment> content;
        long total;
        if (principal.isCompanyType()) {
            content = driverRebateEnchashmentMapper
                .selectByPage(employId, likeParam, page * limit, limit, null);
            total = driverRebateEnchashmentMapper.countByPage(employId, likeParam, null);
        } else {
            Long companyId = principal.getCompanyId();
            content = driverRebateEnchashmentMapper
                .selectByPage(employId, likeParam, page * limit, limit, companyId);
            total = driverRebateEnchashmentMapper.countByPage(employId, likeParam, companyId);
        }

        return new PageImpl<DriverRebateEnchashment>(content, pageable, total);

    }

    public List<DriverRebateEnchashment> listByEmploy(Long employId, String param) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        String likeParam = null;
        Long[] companyIds = null;

        if (null != principal) {
            if (!principal.isCompanyType()) {
                companyIds = new Long[1];
                companyIds[0] = principal.getCompanyId();
            }
        }

        if (StringUtils.isNotBlank(param)) {
            likeParam = "%" + param + "%";
        }

        List<DriverRebateEnchashment> content = driverRebateEnchashmentMapper.selectBylist(
            employId, likeParam);
        return content;
    }

    @Transactional(rollbackFor = Exception.class)
    public DriverRebateEnchashment insertRecord(DriverRebateEnchashment driverRebateEnchashment) {

        driverRebateEnchashmentMapper.insertRecord(driverRebateEnchashment);

        return driverRebateEnchashment;
    }

    public DriverRebateEnchashment findOne(Long id) {

        return driverRebateEnchashmentMapper.selectByPrimaryKey(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(DriverRebateEnchashment driverRebateEnchashment) {

        driverRebateEnchashmentMapper.deleteByPrimaryKey(driverRebateEnchashment.getId());

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateByPrimaryKey(DriverRebateEnchashment driverRebateEnchashment) {

        return driverRebateEnchashmentMapper.updateByPrimaryKey(driverRebateEnchashment);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void audit(DriverRebateEnchashment driverRebateEnchashment, Driver driver,
        String result) {
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        BigDecimal money = driverRebateEnchashment.getOpRebateMoney();
        String memo = "推荐奖励提现（" + money.doubleValue() + "）";

        if (result.equals("success")) {
            driverRebateEnchashment.setStatus(DriverRebateEnchashment.STATUS_SUCCESS);
            driverRebateEnchashmentMapper.updateByPrimaryKey(driverRebateEnchashment);

            driver.setVirtual(driver.getVirtual().add(money));
            DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
            driverPaymentsRecord.setMoney(money);
            driverPaymentsRecord.setAfterMoney(driver.getVirtual());
            driverPaymentsRecord.setDriverId(driver.getId());
            driverPaymentsRecord.setDriverRealName(driver.getRealname());
            driverPaymentsRecord.setDriverUserName(driver.getUsername());
            driverPaymentsRecord.setDriverPhone(driver.getPhone());
            driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
            driverPaymentsRecord
                .setRecordType(DriverPaymentsRecord.CONSUMEDRECORD_TYPE_DRIVER_REBATE_ENCHASHMENT);
            driverPaymentsRecord
                .setRcType(DriverPaymentsRecord.DRIVER_TUIJIAN_JIANGLI);
            if (StringUtils.isBlank(driverRebateEnchashment.getMemo())) {
                driverPaymentsRecord.setMemo(driverRebateEnchashment.getMemo());
            } else {
                driverPaymentsRecord.setMemo("");
            }

            driverPaymentsRecord.setOperating(principal.getUsername());
            driverPaymentsRecord.setHappend(new Date());
            driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

            Company company = companyService.findOne(driver.getCompanyId());

            StringBuilder sb_f = new StringBuilder();
            FinancialRecord financialRecord = new FinancialRecord();
            sb_f.append(OrderNumberConfig.FINANCIAL_DRIVER_REBATE_REWARD);
            sb_f.append(OrderNumberConfig.FINANCIAL_WHO_DRIVER);//对象 服务人员
            sb_f.append(DateTimeUtils.DATE_FORMAT_yyyyMMdd.format(new Date()));//年月日时间
            sb_f.append(
                OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));//流水号
            financialRecord.setCode(sb_f.toString());
            financialRecord.setCompanyId(company.getId());
            financialRecord.setCompanyName(company.getAbbreviation());
            financialRecord.setOrderCompanyId(company.getId());
            financialRecord.setOrderCompanyName(company.getAbbreviation());
            financialRecord.setMemo(
                "推荐奖励提成审核通过 司机[" + driver.getUsername() + " 金额:" + money.doubleValue() + " 审核员:"
                    + principal.getUsername());
            financialRecord.setMoney(money);
            financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
            financialRecord.setWho(driver.getRealname());
            financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_MEMBERREBATE_REWARD);
            financialRecordMapper.insertRecord(financialRecord);

            memo += " 已通过";
        } else if (result.equals("turndown")) {
            driverRebateEnchashment.setStatus(DriverRebateEnchashment.STATUS_TURNDOWN);
            driverRebateEnchashmentMapper.updateByPrimaryKey(driverRebateEnchashment);

            driver.setRebateMoney(driver.getRebateMoney().add(
                driverRebateEnchashment.getOpRebateMoney()));

            driverMapper.updateDriverRebate(driver.getRebateMoney(), driver.getId());

            DriverRebatePaymentRecord one = new DriverRebatePaymentRecord();
            one.setMoney(money);
            one.setAfterMoney(driver.getRebateMoney());
            one.setRecordType(DriverPaymentsRecord.RECHARGE_TYPE_DRIVER_REBATE_ENCHASHMENT);
            one.setMemo("推荐奖励提成被驳回, 返回奖励" + money.doubleValue() + "元。");
            one.setOperating(principal.getUsername());
            one.setDriverId(driver.getId());
            driverRebatePaymentRecordMapper.insertRecord(one);
            memo += " 已驳回";
        }

//        Notice notice = new Notice();
//        notice.setCompanyId(principal.getCompanyId());
//        notice.setContent(memo);
//        notice.setOperating(principal.getUsername());
//        noticeMapper.insertRecord(notice);
//
//        NoticeXDriver noticeXDriver = new NoticeXDriver();
//        noticeXDriver.setDriverId(driver.getId());
//        noticeXDriver.setNoticeId(notice.getId());
//        noticeXDriver.setHasRead(false);
//        noticeXDriverMapper.insertRecord(noticeXDriver);
//
//        List<Driver> driverList = new ArrayList<Driver>();
//        driverList.add(driver);
//
//        NoticeEvent noticeEvent = new NoticeEvent(notice, driverList);
//        applicationEventMulticaster.multicastEvent(noticeEvent);
    }

    @Transactional(rollbackFor = Exception.class)
    public void apply(Driver driver, BigDecimal money) {
        driver.setRebateMoney(driver.getRebateMoney().subtract(money));

        driverService.updateRebateMoney(driver.getRebateMoney(), driver.getId());

        DriverRebatePaymentRecord one = new DriverRebatePaymentRecord();
        one.setMoney(money.negate());
        one.setAfterMoney(driver.getRebateMoney());
        one.setRecordType(DriverPaymentsRecord.CONSUMEDRECORD_TYPE_DRIVER_REBATE_ENCHASHMENT);
        one.setMemo("司机[" + driver.getUsername() + "]推荐奖励提成申请,扣除奖励" + money.doubleValue() + "元。");
        one.setOperating(DriverRebatePaymentRecord.OPERATING_SYS);
        one.setDriverId(driver.getId());
        driverRebatePaymentRecordMapper.insertRecord(one);

        DriverRebateEnchashment driverRebateEnchashment = new DriverRebateEnchashment();
        driverRebateEnchashment.setStatus(DriverRebateEnchashment.STATUS_WAIT);
        driverRebateEnchashment.setEmployPhone(driver.getPhone());
        driverRebateEnchashment.setEmployId(driver.getId());
        driverRebateEnchashment.setEmployUserName(driver.getUsername());
        driverRebateEnchashment.setEmployRealName(driver.getRealname());
        driverRebateEnchashment.setOpRebateMoney(money);
        driverRebateEnchashment.setAfterRebateMoney(driver.getRebateMoney());
        driverRebateEnchashment
            .setMemo("司机[" + driver.getUsername() + "申请提取推荐奖励" + money.doubleValue() + "元");
        driverRebateEnchashment.setCompanyId(driver.getCompanyId());
        driverRebateEnchashment
            .setCompanyName(companyService.findOne(driver.getCompanyId()).getCompanyName());
        this.insertRecord(driverRebateEnchashment);
    }
}